var SIGN_REGEXP = /([yMdhsm])(\1*)/g
var DEFAULT_PATTERN = 'yyyy-MM-dd'
function padding(s, len) {
  len = len - (s + '').length
  for (let i = 0; i < len; i++) { s = '0' + s }
  return s
}

export default {
  getQueryStringByName: function(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    var context = ''
    if (r != null) { context = r[2] }
    reg = null
    r = null
    return context == null || context === '' || context === 'undefined' ? '' : context
  },
  formatDate: {

    format: function(date, pattern) {
      pattern = pattern || DEFAULT_PATTERN
      return pattern.replace(SIGN_REGEXP, function($0) {
        switch ($0.charAt(0)) {
          case 'y': return padding(date.getFullYear(), $0.length)
          case 'M': return padding(date.getMonth() + 1, $0.length)
          case 'd': return padding(date.getDate(), $0.length)
          case 'w': return date.getDay() + 1
          case 'h': return padding(date.getHours(), $0.length)
          case 'm': return padding(date.getMinutes(), $0.length)
          case 's': return padding(date.getSeconds(), $0.length)
        }
      })
    },
    parse: function(dateString, pattern) {
      var matchs1 = pattern.match(SIGN_REGEXP)
      var matchs2 = dateString.match(/(\d)+/g)
      if (matchs1.length === matchs2.length) {
        var _date = new Date(1970, 0, 1)
        for (var i = 0; i < matchs1.length; i++) {
          var _int = parseInt(matchs2[i])
          var sign = matchs1[i]
          switch (sign.charAt(0)) {
            case 'y': _date.setFullYear(_int); break
            case 'M': _date.setMonth(_int - 1); break
            case 'd': _date.setDate(_int); break
            case 'h': _date.setHours(_int); break
            case 'm': _date.setMinutes(_int); break
            case 's': _date.setSeconds(_int); break
          }
        }
        return _date
      }
      return null
    }

  },
  http: {
    parseFilename: function(res) {
      let filename = ''
      const disposition = res.headers['content-disposition']
      if (disposition && disposition.indexOf('attachment') !== -1) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        const matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
          filename = window.decodeURI(filename)
        }
      }
      return filename
    },
    contentType: function(res) {
      const h = res.headers || {}
      return h['content-type']
    },
    /**
         * 是否返回json内容
         * @param res 响应对象
         * @returns {boolean} true表示是json内容,否则不是
         */
    jsonContent: function(res) {
      const content = this.contentType(res)
      return !!(content && content.indexOf('json') !== -1)
    }
  },
  transform: {
    arrayBuffer2Str: function(arrayBuffer) {
      let str = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer))
      str = escape(str)
      str = decodeURIComponent(str)
      return str
    }
  },
  downloader: {
    /**
         * 下载文件
         * @param arrayBuffer 文件内容缓冲
         * @param fileName 文件名
         */
    downloadBlob(arrayBuffer, fileName) {
      const blob = new Blob([arrayBuffer])
      if (window.navigator.msSaveBlob) {
        try {
          window.navigator.msSaveBlob(blob, fileName)
        } catch (e) {
          console.log(e)
        }
      } else {
        const fileURL = window.URL.createObjectURL(blob)
        const fileLink = document.createElement('a')

        fileLink.href = fileURL
        fileLink.setAttribute('download', fileName)
        document.body.appendChild(fileLink)

        fileLink.click()

        document.body.removeChild(fileLink) // 下载完成移除元素
        window.URL.revokeObjectURL(fileURL) // 释放掉blob对象
      }
    }
  },
  currency: {
    format: function(money) {
      let cost = parseInt(money)
      if (isNaN(cost)) {
        return money
      }
      cost = cost / 100
      let s = cost.toString()
      let idx = s.indexOf('.')
      if (idx < 0) {
        idx = s.length
        s += '.'
      }
      while (s.length < (idx + 3)) {
        s += 0
      }
      return s
    }
  }

}
